using MediatR;
using Microsoft.AspNetCore.Mvc;
using S.M.SmartMedical.API.Write.Application.Command;
using S.M.SmartMedical.Domain.DTOs;
using S.M.SmartMedical.ErrorCode;

namespace S.M.SmartMedical.API.Write.Controllers
{
    /// <summary>
    /// 用户管理控制器（写操作）
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class UserController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<UserController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator">中介者</param>
        /// <param name="logger">日志记录器</param>
        public UserController(IMediator mediator, ILogger<UserController> logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="userRegisterDto">用户注册信息</param>
        /// <returns>注册结果</returns>
        [HttpPost("register")]
        public async Task<APIResult<UserInfoDto>> Register([FromBody] UserRegisterDto userRegisterDto)
        {
            try
            {
                _logger.LogInformation("接收到用户注册请求，用户名：{UserName}", userRegisterDto.UserName);

                // 验证模型
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Values
                        .SelectMany(v => v.Errors)
                        .Select(e => e.ErrorMessage)
                        .ToList();
                    
                    _logger.LogWarning("用户注册参数验证失败：{Errors}", string.Join(", ", errors));
                    
                    return new APIResult<UserInfoDto>
                    {
                        Code = APIEnum.Fail,
                        Message = string.Join(", ", errors),
                        Data = null!
                    };
                }

                // 发送注册命令
                var command = new RegisterUserCommand(userRegisterDto);
                var result = await _mediator.Send(command);

                _logger.LogInformation("用户注册请求处理完成，用户名：{UserName}，结果：{Code}", 
                    userRegisterDto.UserName, result.Code);

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用户注册接口异常，用户名：{UserName}", userRegisterDto.UserName);
                return new APIResult<UserInfoDto>
                {
                    Code = APIEnum.Fail,
                    Message = "注册失败，系统异常",
                    Data = null!
                };
            }
        }
    }
}